<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="container"></div>
    <button id="btn-change">change</button>
    <script>
        (function () {

            var snabbdom = window.snabbdom;

            // 定义patch
            var patch = snabbdom.init([
                snabbdom_class,
                snabbdom_props,
                snabbdom_style,
                snabbdom_eventlisteners,
            ])
            // 定义h
            var h = snabbdom.h;
            var container = document.getElementById("container");
            var btn = document.getElementById('btn-change');
            var data = [{
                    name: "张三",
                    age: 20,
                    address: '北京'
                },
                {
                    name: "李四",
                    age: 30,
                    address: '上海'
                },
                {
                    name: "王五",
                    age: 40,
                    address: '深圳'
                }
            ]
            data.unshift({
                name:"姓名",
                age:"年龄",
                address:"地址"
            })
            var vnode=null;
            function render(data) {
                // 初始化节点或重新编写更改后的data数据
                var newVnode=h("table",{},data.map(item=>{
                    var tds=[];
                    for (const key in item) {
                        if (item.hasOwnProperty(key)) {
                            const element = item[key];
                            tds.push(h('td',{},element))
                        }
                    }
                    return h('tr',{},tds);  
                }));

                // 判断是否是第一次渲染
                if(vnode){
                    // 第二次是进行新老节点对比后再渲染
                    patch(vnode,newVnode);
                }else{
                    // 第一次渲染在容器里
                    patch(container,vnode);
                }

                vnode=newVnode;
            }
            // 第一次渲染数据
            render(data);
            
            // 点击按钮更改data数据
            btn.addEventListener('click', function () {
                data[1].age = 50;
                data[1].address = "成都";

                //  re-render 改变data后重新render
                render(data);
            }, false)
        })();
    </script>
</body>

</html>